import React from 'react'
import { Input, Select, Checkbox, Radio, Upload, Icon, Modal, Form, Button, message } from 'antd'
import PropTypes from 'prop-types'
import axios from 'axios'
import API from '../../../../api/Goods/goods'
import './template.less'
import { withRouter } from 'react-router-dom'
const Option = Select.Option
const CheckboxGroup = Checkbox.Group
const RadioGroup = Radio.Group
const FormItem = Form.Item

class IcsComponentsSupplierFilterForm extends React.Component {
    state = {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        goods_id: '',
        goodsImg: [],

        canChang: true
    }
    componentWillReceiveProps (nextProps) {
        if (!this.state.canChang) return
        if ('goodsImg' in nextProps && nextProps.goodsImg !== null ) {
            this.setState({goodsImg: nextProps.goodsImg, canChang: false})
        }
        if ('shop_id' in nextProps) {
            this.setState({shop_id: nextProps.shop_id})
        }
        if ('goodsInfo' in nextProps && typeof nextProps.goodsInfo === 'object' && nextProps.goodsInfo.hasOwnProperty('goods_id')) {
            this.setState({goodsInfo: nextProps.goodsInfo})
        }
    }

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    componentDidMount () {
        if (this.props.history.location.state) {
            this.setState({goods_id: this.props.history.location.state.goods_id}, () => {
            })
        }
        this.getShopList()
    }
    handleSearch = (e) => {
        e.preventDefault()
        this.props.form.validateFields((err, values) => {
            if (err) return
            values['cat_id'] = this.props.cat_id
            if (this.state.goodsImg.length < 0) {
                message.error('请上传商家图片！')
            }
            values.store_type = 1
            if (this.state.goodsImg.length > 0) {
                values.goods_img = this.state.goodsImg.map(v => {
                    let obj = {
                        name: v.name,
                        url: v.url,
                        uid: v.uid
                    }
                    return obj
                })
            }
            if (this.state.goods_id) {
                values.goods_id = this.state.goods_id
                this.editData(values)
            } else {
                this.addData(values)
            }
        })
    }
    addData = (values) => {
        API.createGoods(values).then(res => {
            if (res.error === 0) {
                message.success('添加成功！')
                this.setState({showViewer: false})
                setTimeout(() => {
                    this.props.history.push("/business/detail/" + this.state.shop_id)
                }, 500)
            } else {
                message.error(res.msg || '添加失败！')
            }
        })
    }
    editData = (values) => {
        API.editGoods(values).then(res => {
            if (res.error === 0) {
                message.success('编辑成功！')
                this.setState({showViewer: false})
                setTimeout(() => {
                    this.props.history.push("/goods/list",{shop_id: this.state.shop_id, shop_name: this.state.goodsInfo.shop_name})
                }, 500)
            } else {
                message.error(res.msg || '编辑失败！')
            }
        })
    }
    handleChange = (info) => {
        let fileList = info.fileList;
        fileList = fileList.map((file) => {
            if (file.response) {
                console.log(file.response.data.src)
                file.url = file.response.data.src;
            }
            return file;
        });
        this.setState({ goodsImg: fileList}, () => {
            // this.props.onChange(this.state.fileList)
        });
    }
    getShopList = () => {
        API.getShopList({page: 1, pageSize: 100, audit_status: 10, shop_status: 1}).then(res => {
            this.setState({shopList: res.data.listData})
        })
    }
    changeStore= (val) => {
    }
    render () {
        const children = [];
        if (this.state.shopList && this.state.shopList.length > 0) {
            for (let i = 0; i < this.state.shopList.length; i++) {
                children.push(<Option key={this.state.shopList[i].id} value={this.state.shopList[i].id}>{this.state.shopList[i].shop_name}</Option>)
            }
        }
        let options = []
        if (this.props.shopStoreList && this.props.shopStoreList.length) {
            this.props.shopStoreList.forEach((v) => {
                options.push({label: v.store_name, value: v.id})
            })
        }
        const { fileList } = this.state
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        )
        const { getFieldDecorator } = this.props.form
        let action = axios.defaults.baseURL + '/Common/uploadImg'
        return (
            <Form
                layout="inline"
                className="supplier-filter"
                onSubmit={this.handleSearch}
            >
                <div className='template-container'>
                    <div className="base-info" style={{paddingLeft: 20}}>
                        <div className='base-title'>基本信息</div>
                        <div className='info'>
                            <FormItem
                                label="商品名称"
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 12 }}
                            >
                                {getFieldDecorator('goods_name', {
                                    rules: [{
                                        required: true, message: '请输入商品名称',
                                    }],
                                    initialValue: this.state.goodsInfo? this.state.goodsInfo.goods_name: ''
                                })(
                                    <Input placeholder="请输入商品名称" />
                                )}
                            </FormItem>
                            <FormItem
                                label="副标题"
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 12 }}
                            >
                                {getFieldDecorator('goods_name_ori', {
                                    rules: [{
                                        required: true, message: '请输入副标题',
                                    }],
                                    initialValue: this.state.goodsInfo? this.state.goodsInfo.goods_name_ori: ''
                                })(
                                    <Input placeholder="请输入副标题" />
                                )}
                            </FormItem>
                            <FormItem
                                label="商品售价"
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 12 }}
                            >
                                {getFieldDecorator('sale_price', {
                                    rules: [{
                                        required: true, message: '请输入商品售价',
                                    }],
                                    initialValue: this.state.goodsInfo? this.state.goodsInfo.sale_price: ''
                                })(
                                    <Input placeholder="请输入商品售价" />
                                )}
                            </FormItem>
                            <FormItem
                                label="归属商家"
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 12 }}
                            >
                                {getFieldDecorator('shop_id', {
                                    rules: [{
                                        required: true, message: '请选择归属商家',
                                    }],
                                    initialValue: this.state.goodsInfo? this.state.goodsInfo.shop_id: this.state.shop_id ? this.state.shop_id : ''
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        placeholder="请选择"
                                        onChange={this.props.reGetStoreList}
                                    >
                                        {children}
                                    </Select>
                                )}
                            </FormItem>
                            <FormItem
                                label="在售门店"
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 12 }}
                            >
                                {getFieldDecorator('store_id', {
                                    rules: [{
                                        required: true, message: '请在售门店',
                                    }],
                                    initialValue: this.props.checkedShopStore? this.props.checkedShopStore: []
                                })(
                                    <CheckboxGroup options={options} onChange={this.changeStore}/>
                                )}
                            </FormItem>
                        </div>
                    </div>
                    <div className='base-info' style={{paddingLeft: 40}}>
                        <div className='base-title'>上传图片</div>
                        <div className='info'>
                            <div className='type'>
                                <RadioGroup onChange={this.onChange}>
                                    <Radio value={1} checked>上传主图</Radio>
                                </RadioGroup>
                            </div>
                            <div className='img-container'>
                                <div className="notice">
                                    <p>1、图片至少上传1张，最多可以传8张，单张图片大小不能超过4M</p>
                                    <p>2、建议图片尺寸为：1024px*678px，前台页面即可根据不同页面显示的图片的大小进行放大和缩小。</p>
                                    <p>3、图片质量要清晰、不能虚化、不能涉及广告违法图片。</p>
                                </div>
                                <div className="clearfix">
                                    <Upload
                                        name="img_file"
                                        action={action}
                                        headers={{authorization: 'authorization-text' }}
                                        listType="picture-card"
                                        method="post"
                                        fileList={this.state.goodsImg}
                                        onPreview={this.handlePreview}
                                        onChange={this.handleChange}
                                    >
                                        {fileList.length >= 3 ? null : uploadButton}
                                    </Upload>
                                    <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
                                        <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                                    </Modal>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="btns" style={{paddingLeft: 40, marginTop: 20}}>
                        <Button type="primary" htmlType="submit" >提交</Button>
                    </div>
                </div>
            </Form>
        )
    }
}

IcsComponentsSupplierFilterForm.propTypes = {
    cat_name: PropTypes.any,
    cat_id: PropTypes.any,
    getFieldDecorator: PropTypes.func,
    doSearch: PropTypes.func,
    form: PropTypes.object,
    goodsInfo: PropTypes.any,
    goodsImg: PropTypes.array,
    shopStoreList: PropTypes.array,
    reGetStoreList: PropTypes.func,
    checkedShopStore: PropTypes.array

}
const IcsComponentsSupplierFilter = Form.create()(IcsComponentsSupplierFilterForm)
export default withRouter(IcsComponentsSupplierFilter)
